package com.xingyun.mvp.ui.home.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.jess.arms.base.BaseFragment;
import com.jess.arms.base.DefaultAdapter;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.widget.autolayout.AutoToolbar;
import com.paginate.Paginate;
import com.xingyun.R;
import com.xingyun.di.component.DaggerMainPagerComponent;
import com.xingyun.di.module.MainPagerModule;
import com.xingyun.mvp.contract.MainPagerContract;
import com.xingyun.mvp.presenter.MainPagerPresenter;
import com.xingyun.mvp.ui.home.activity.ArticleActivity;
import com.xingyun.mvp.ui.home.adapter.MainPagerAdapter;
import com.xingyun.mvp.ui.widget.SpacesItemDecoration;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import timber.log.Timber;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class MainPagerFragment extends BaseFragment<MainPagerPresenter> implements MainPagerContract.View, SwipeRefreshLayout.OnRefreshListener {

    Unbinder unbinder;
    @BindView(R.id.rv_main)
    RecyclerView rvMain;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.toolbar_back)
    ImageView toolbarBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.toolbar)
    AutoToolbar toolbar;
    private View mRootView;

    private Paginate mPaginate;
    private boolean isLoadingMore;

    @Inject
    RecyclerView.LayoutManager mLayoutManager;
    @Inject
    MainPagerAdapter mAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    public static MainPagerFragment newInstance() {
        MainPagerFragment fragment = new MainPagerFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(AppComponent appComponent) {
        DaggerMainPagerComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .mainPagerModule(new MainPagerModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (mRootView == null)
            mRootView = inflater.inflate(R.layout.fragment_main_pager, container, false);
        return mRootView;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        ((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
        ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(false);
        toolbarTitle.setText("每日一文");
        initRecyclerView();
        mAdapter.setOnItemClickListener(dataBean -> {
            Intent intent = new Intent(getActivity(), ArticleActivity.class);
            intent.putExtra("ArticleMsg", dataBean);
            launchActivity(intent);
        });
        rvMain.setAdapter(mAdapter);
        initPaginate();
        mPresenter.getArticle(true);
    }


    /**
     * 此方法是让外部调用使fragment做一些操作的,比如说外部的activity想让fragment对象执行一些方法,
     * 建议在有多个需要让外界调用的方法时,统一传Message,通过what字段,来区分不同的方法,在setData
     * 方法中就可以switch做不同的操作,这样就可以用统一的入口方法做不同的事
     * <p>
     * 使用此方法时请注意调用时fragment的生命周期,如果调用此setData方法时onCreate还没执行
     * setData里却调用了presenter的方法时,是会报空的,因为dagger注入是在onCreated方法中执行的,然后才创建的presenter
     * 如果要做一些初始化操作,可以不必让外部调setData,在initData中初始化就可以了
     *
     * @param data
     */
    @Override
    public void setData(Object data) {

    }

    /**
     * 初始化RecyclerView
     */
    private void initRecyclerView() {
        swipeRefreshLayout.setOnRefreshListener(this);
        int spacingInPixels = 30;
        rvMain.addItemDecoration(new SpacesItemDecoration(spacingInPixels));
        ArmsUtils.configRecycleView(rvMain, mLayoutManager);
    }


    @Override
    public void showLoading() {
        Timber.tag(TAG).w("showLoading");
        swipeRefreshLayout.setRefreshing(true);
    }

    @Override
    public void hideLoading() {
        Timber.tag(TAG).w("hideLoading");
        swipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    @Override
    public void startLoadMore() {
        isLoadingMore = true;
    }

    @Override
    public void endLoadMore() {
        isLoadingMore = false;
    }

    @Override
    public void onRefresh() {
        mPresenter.getArticle(true);
    }

    @Override
    public void onDestroyView() {
        DefaultAdapter.releaseAllHolder(rvMain);
        super.onDestroyView();
        this.mPaginate = null;
        unbinder.unbind();
    }

    /**
     * 初始化Paginate,用于加载更多
     */
    private void initPaginate() {
        if (mPaginate == null) {
            Paginate.Callbacks callbacks = new Paginate.Callbacks() {
                @Override
                public void onLoadMore() {
                    mPresenter.getArticle(false);
                }

                @Override
                public boolean isLoading() {
                    return isLoadingMore;
                }

                @Override
                public boolean hasLoadedAllItems() {
                    return false;
                }
            };

            mPaginate = Paginate.with(rvMain, callbacks)
                    .setLoadingTriggerThreshold(0)
                    .build();
            mPaginate.setHasMoreDataToLoad(false);
        }
    }
}
